// 执行 node index.js
const fs = require('fs')

const sourceFilePath = './iconfont.js'
const tplFilePath = './src/iconfont.tpl'
const outputPath = './myiconfont.ets'

function readIconfontJS() {
  let source = fs.readFileSync(sourceFilePath, 'utf-8')
  // console.log(source)

  let pattSymbol = /<symbol(.)*?<\/symbol>/g
  let symbolArr = source.match(pattSymbol)
  // console.log(symbolArr.length)

  let iconfontData = []
  symbolArr.forEach((symbolText, i) => {
    let obj = {}
    //获取名称id
    let pattName = /id="((.)*?)?"/
    let name = symbolText.match(pattName)[1]
    // console.log(name) //icon-name

    //获取viewBox
    let pattViewBox = /viewBox="((.)*?)?"/
    let viewBox = symbolText.match(pattViewBox)[1].split(' ')
    // console.log(viewBox) //[0,0,1024,1024]

    //获取绘制路径
    let pattPath = /<path d="((.)*?)?"/
    let path = symbolText.match(pattPath)[1]
    // console.log(path)

    obj = {
      name: name,
      viewBox: viewBox,
      path: path
    }

    iconfontData.push(obj)
  })

  // console.log(iconfontData)
  return iconfontData
}

function generateBuilderDecoration(index, path, viewBox) {
  return `
    @Builder IconfontComponent${index}() {
      IconfontDesigner({
        path: '${path}',
        viewBox: {
          x: ${viewBox[0]},
          y: ${viewBox[1]},
          width: ${viewBox[2]},
          height: ${viewBox[3]}
        },
        fontSize: this.style.fontSize,
        fontColor: this.style.fontColor,
        fontWeight: this.style.fontWeight
      })
    }
    `
}

function generateBuilderOptions(index, name) {
  return `
  if (this.fontName == '${name}') {
    this.IconfontComponent${index}()
  }
  `
}

function generateETS($structName, $builder, $options) {
  let template = fs.readFileSync(tplFilePath, 'utf-8')
  template = template.replace('{{$structName}}', $structName)
  template = template.replace('{{$builder}}', $builder)
  template = template.replace('{{$options}}', $options)
  // console.log(template)

  fs.writeFileSync(outputPath, template, {
    encoding: 'utf8',
    flag: 'w'
  })
}

function main() {
  let $structName = 'MyIconfont'

  //读取处理数据
  let data = readIconfontJS()
  let $builder = ''
  let $options = ''

  data.forEach((item, index) => {
    $builder += generateBuilderDecoration(index, item.path, item.viewBox)
    $options += generateBuilderOptions(index, item.name)
  })
  // console.log($builder)
  // console.log($options)

  generateETS($structName, $builder, $options)
}

main()
